import {createRouter, createWebHashHistory, RouteRecordRaw} from "vue-router"
import login from "../views/login.vue"
import home from "../views/home/index.vue"
import surveyList from "../views/home/surveyList.vue"
import myAccount from "../views/home/myAccount.vue"
import mySurvey from "../views/home/mySurvey.vue"
import surveyPublish from "../views/home/surveyPublish.vue"
import surveyReview from "../views/home/surveyReview.vue"
import surveyStatistics from "../views/home/surveyStatistics.vue"
import { getCookie } from "../utils/common"


const routes: Array<RouteRecordRaw> = [
    {
        name: 'login',
        path: '/',
        meta: {title: "Login In", menu:false},
        component: login
    },
    {
        name: '',
        path: '/home',
        meta: {title: "Home", menu:true},
        component: home,
        children: [
            {
                path: '/',
                component: surveyList,
            },
            {
              name: 'surveyList',
              path: '/surveyList',
              component: surveyList,
            },
            {
                name: 'myAccount',
                path: '/myAccount',
                component: myAccount,
            },
            {
                name: 'mySurvey',
                path: '/mySurvey',
                component: mySurvey,
            },
            {
                name: 'surveyPublish',
                path: '/surveyPublish',
                component: surveyPublish,
              },
              {
                  name: 'surveyReview',
                  path: '/surveyReview',
                  component: surveyReview,
              },
              {
                  name: 'surveyStatistics',
                  path: '/surveyStatistics',
                  component: surveyStatistics,
              }
          ],
    }
    
]
const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

router.beforeEach((to, from, next) => {
    let token = getCookie('survey_user_token')
    const isLoggedIn = !!token || !(from.meta.title);

    if (to.name !== 'login' && !isLoggedIn) {
        console.log(123)
        // 如果用户未登录且尝试访问非登录页面，则重定向到登录页
        next({ path: '/'});
    } else {
        // 如果用户已登录或者尝试访问登录页面，则允许跳转
        next();
    }
});
export default router